package com.jcl.core.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @ClassName JclHttpClient

 * @Author yyliu
 * @Date 2018/10/16 14:14
 * @Version 1.0
 **/
public class HttpRequest {

    private static final Logger logger                     = LoggerFactory.getLogger(HttpRequest.class);

    public static final String GZIP_CONTENT_TYPE          = "application/x-gzip";

    public static final String JSON_CONTENT_TYPE          = "application/json; charset=UTF-8";

    public static final String DEFAULT_CONTENT_TYPE       = "application/x-www-form-urlencoded; charset=UTF-8";

    private static final String USER_AGENT                 = "Mozilla/5.0 (Linux; Android 4.4.4;  en-us; Nexus 4 Build/JOP40D) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2307.2 Mobile Safari/537.36";

    public static final int DEFAULT_SOCKET_TIMEOUT         = 10000;

    public static final String  DEFAULT_CHARSET            = "UTF-8";

    public static final String HTTP_POST_METHOD            = "POST";

    public static final String HTTP_GET_METHOD             = "GET";


    private HttpRequest(){}

    public static void main(String[] args) throws UnsupportedEncodingException {

        String json = " {\"resumeNo\":\"zkMvCIKRj6z1h0dkNS0KLA\",\"Referer\":\"\":\"https://rd5.zhaopin.com/resume/detail?keyword=java&resumeNo=zkMvCIKRj6z1h0dkNS0KLA_1_1%3B4FA87DAACF63EB2923440C1FAAEED720%3B1539765996667&openFrom=1\",\"r\",\"resumeNo_k_t\":\"zkMvCIKRj6z1h0dkNS0KLA_1_1%3B4FA87DAACF63EB2923440C1FAAEED720%3B1539765996667\"}";
        String dd = Base64.getEncoder().encodeToString(
                json.getBytes("utf-8"));
        Map<String, Object> params = new HashMap<>();

        params.put("account", "");
        params.put("userName", "zhangsan");
        params.put("passWord", "lisis");
        params.put("buyResumeContext", json);
        params.put("taskType", "buy-resume");
        params.put("tenantId", "dds"); // corpCode + resumeId
        String message = httpPost("http://47.99.107.88:8762/job/v1/buy/tasks", JSON_CONTENT_TYPE, params);

        System.out.println(message);
    }

    /* *
     * @Author yyliu
     * @Description //TODO
     * @Date 14:23 2018/10/16
     * @Param [url, params]
     * @return
     **/
    public static String httpPost(String url, String contentType, Map<String, Object> params){

        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader(HTTP.USER_AGENT, USER_AGENT);
        if(null != contentType){

            httpPost.setHeader(HTTP.CONTENT_TYPE, contentType);
        }else{
            httpPost.setHeader(HTTP.CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
        }

        try {
            if(contentType.equals(JSON_CONTENT_TYPE)){
                // 设置参数
                String param = JSONObject.toJSONString(params);
                System.out.println("----------------   " + param);
                httpPost.setEntity(new StringEntity(param, DEFAULT_CHARSET));
            }else if(contentType.equals(DEFAULT_CONTENT_TYPE)){
                List<NameValuePair> formParams = new ArrayList<>();
                if(null != params && params.size() > 0){
                    for(Map.Entry<String, Object> entity: params.entrySet()){
                        formParams.add(new BasicNameValuePair(entity.getKey(), entity.getValue().toString()));
                    }
                    logger.debug("send post params is : {} " + formParams.toString());
                }
                // 设置参数
                httpPost.setEntity(new UrlEncodedFormEntity(formParams, DEFAULT_CHARSET));
            }
            RequestConfig config = RequestConfig.custom().setSocketTimeout(DEFAULT_SOCKET_TIMEOUT)
                    .setConnectTimeout(DEFAULT_SOCKET_TIMEOUT).build();
            httpPost.setConfig(config);

            return send(httpClient, httpPost);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

   /* *
    * @Author yyliu
    * @Description //TODO
    * @Date 14:23 2018/10/16
    * @Param [url, params]
    * @return
    **/
    public static String httpGet(String url){

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader(HTTP.USER_AGENT, USER_AGENT);
        httpGet.addHeader(HTTP.CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
        try {

            RequestConfig config = RequestConfig.custom().setSocketTimeout(DEFAULT_SOCKET_TIMEOUT)
                    .setConnectTimeout(DEFAULT_SOCKET_TIMEOUT).build();
            httpGet.setConfig(config);

            return send(httpClient, httpGet);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return null;
    }

    public static byte[] getByte(String url){

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader(HTTP.USER_AGENT, USER_AGENT);
        httpGet.addHeader(HTTP.CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
        try {

            RequestConfig config = RequestConfig.custom().setSocketTimeout(DEFAULT_SOCKET_TIMEOUT)
                    .setConnectTimeout(DEFAULT_SOCKET_TIMEOUT).build();
            httpGet.setConfig(config);
            CloseableHttpResponse response = null;
            try{
                response = httpClient.execute(httpGet);
                return EntityUtils.toByteArray(response.getEntity());
            }catch (IOException e) {
                logger.error(e.getMessage(), e);
            }finally {
                if(null != response){
                    try {
                        response.close();
                    } catch (IOException e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return null;
    }

    /* *
     * @Author yyliu
     * @Description //TODO 
     * @Date 15:03 2018/10/16
     * @Param [httpClient, request]
     * @return java.lang.String
     **/
    private static String send(CloseableHttpClient httpClient, HttpUriRequest request){
        String message = null;
        CloseableHttpResponse response = null;
        try{
            response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();
            message =  EntityUtils.toString(entity, DEFAULT_CHARSET);
        }catch (IOException e) {
            logger.error(e.getMessage(), e);
        }finally {
            if(null != response){
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        return message;

    }



}
